package com.fan.cachewebview.pool

import android.app.Activity
import android.content.Context
import android.content.MutableContextWrapper
import androidx.core.util.Pools


/**
 * @description $
 * @date: 2022/3/13 10:43
 * @author: fan
 */
object WebViewCacheHolder {

    private const val MAX_POOL_SIZE = 2
    private var sPool: Pools.Pool<CacheWebView> = Pools.SynchronizedPool(MAX_POOL_SIZE)

    fun prepare(context: Context) {
        release(acquire(context.applicationContext))
    }

    fun acquire(context: Context): CacheWebView {
        var webView: CacheWebView? = sPool.acquire()
        if (webView == null) {
            var wrapper = MutableContextWrapper(context)
            webView = CacheWebView(wrapper)
        } else {
            var wrapper = webView.context as MutableContextWrapper
            wrapper.baseContext = context
        }
        return webView
    }

    fun release(webView: CacheWebView?) {
        try {
            if (webView == null) {
                return
            }
            webView.release()

            var wrapper = webView.context as MutableContextWrapper
            wrapper.baseContext = wrapper.applicationContext
            sPool.release(webView)

            if (webView.context is Activity) {
                throw RuntimeException("leaked")
            }
        } catch (e: Exception) {

        }
    }



}